package com.runyun.project.controller;

import com.alibaba.fastjson.JSONArray;
import com.runyun.project.entity.*;
import com.runyun.project.mapper.FileMapper;
import com.runyun.project.mapper.ShareMapper;
import com.runyun.project.mapper.UserMapper;
import com.runyun.project.util.RunYunUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.*;

@RestController
public class ShareController {

    @Resource
    private ShareMapper shareMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private FileMapper fileMapper;

    @GetMapping("/getShares/{userId}")
    public String getShares(@PathVariable("userId") Integer userId) {
        System.out.println("==========" + userId);
        // 查询用户分享
        List<ShareReturn> list = getShareInfo(userId);
        System.out.println(list);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        return RunYunUtils.getJSONString(200, "分享文件信息", map);
    }

    @GetMapping("/getShareds/{userId}")
    public String getShareds(@PathVariable("userId") Integer userId) {
        System.out.println("==========" + userId);
        // 本用户作为被分享用户
        List<SharedReturn> list = getSharedInfo(userId);
        System.out.println(list);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        return RunYunUtils.getJSONString(200, "被分享记录", map);
    }

    /**
     * 获取收藏
     * @param userId
     * @return
     */
    @GetMapping("/getSaves/{userId}")
    public String getSaves(@PathVariable("userId") Integer userId) {
        System.out.println("==========" + userId);
        List<SaveReturn> list = getLikeInfo(userId);
        System.out.println(list);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list);
        return RunYunUtils.getJSONString(200, "被分享记录", map);
    }

    /**
     * 取消分享
     * @param userId
     * @param data
     * @return
     */
    @PostMapping("/cancelShares/{userId}")
    public String cancelShares(@PathVariable("userId") Integer userId, @RequestBody String data) {
        System.out.println(userId + "===this is data =====" + data);
        List<ShareReturn> list = JSONArray.parseArray(data,ShareReturn.class);

        for (ShareReturn shareReturn : list) {
            // 查询文件id
            Integer fileId = fileMapper.queryFileIdByFileName(shareReturn.getFileName());
            Integer sharedUserId = userMapper.queryUserIdByUserName(shareReturn.getSharedUser());
            // 通过用户Id和文件Id删除分享信息
            shareMapper.deleteShareByUserIdAndFileId(userId, sharedUserId ,fileId);
        }
        List<ShareReturn> list1 = getShareInfo(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list1);
        return RunYunUtils.getJSONString(200, "删除成功！", map);
    }

    /**
     * 收藏
     * @param userId
     * @param data
     * @return
     */
    @PostMapping("/saveShares/{userId}")
    public String saveShares(@PathVariable("userId") Integer userId, @RequestBody String data) {
        System.out.println(userId + "===this is data =====" + data);
        // 修改share表like和like_time, 通过文件ID、当前用户ID和分享人ID
        List<SharedReturn> list = JSONArray.parseArray(data,SharedReturn.class);
        for (SharedReturn sharedReturn: list) {
            Integer shareId = userMapper.queryUserIdByUserName(sharedReturn.getShareName());
            Integer fileId = fileMapper.queryFileIdByFileName(sharedReturn.getFileName());
            shareMapper.updateLikeAndLikeTimeBy3Param(shareId, userId, fileId, 1, new Date());
        }
        List<SharedReturn> list1 = getSharedInfo(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list1);
        return RunYunUtils.getJSONString(200, "收藏成功！", map);
    }

    /**
     * 取消收藏： 将数据信息删除
     */
    @PostMapping("/cancelLikes/{userId}")
    public String cancelLikes(@PathVariable("userId") Integer userId, @RequestBody String data) {
        System.out.println(userId + "===this is data =====" + data);
        // 修改share表like为2表示将信息丢弃，通过文件ID、当前用户ID和分享人ID
        List<SaveReturn> list = JSONArray.parseArray(data,SaveReturn.class);
        for (SaveReturn saveReturn: list) {
            Integer shareId = userMapper.queryUserIdByUserName(saveReturn.getShareUser());
            Integer fileId = fileMapper.queryFileIdByFileName(saveReturn.getFilePath() + saveReturn.getFileName());
            shareMapper.updateLikeAndLikeTimeBy3Param(shareId, userId, fileId, 2, new Date());
        }
        List<SaveReturn> list1 = getLikeInfo(userId);
        Map<String, Object> map = new HashMap<>();
        map.put("data", list1);
        return RunYunUtils.getJSONString(200, "取消收藏成功！", map);
    }


    // 一些重复调用的方法
    /**
     * 通过用户ID查询分享的文件
     * @param userId
     * @return
     */
    private List<ShareReturn> getShareInfo(Integer userId) {
        List<Share> shares = shareMapper.queryByUserId(userId);
        System.out.println(shares);
        List<ShareReturn> list = new ArrayList<>();
        for (Share share : shares) {
            ShareReturn shareReturn = new ShareReturn();
            File file = fileMapper.queryById(share.getFileId());
            shareReturn.setFileName(file.getFileName());
            shareReturn.setFileType(file.getFileType());
            shareReturn.setShareDate(RunYunUtils.dateToString(share.getShareTime()));
            shareReturn.setSharedUser(userMapper.queryById(share.getSharedUserId()).getUserName());
            list.add(shareReturn);
        }
        return list;
    }

    /**
     * 查询没有被收藏的分享
     * @param userId
     * @return
     */
    private List<SharedReturn> getSharedInfo(Integer userId) {
        List<Share> shares = shareMapper.queryBySharedUserIdAndLike(userId, 0);
        List<SharedReturn> list = new ArrayList<>();
        for (Share share: shares) {
            SharedReturn sharedReturn = new SharedReturn();
            File file = fileMapper.queryById(share.getFileId());
            sharedReturn.setShareName(userMapper.queryById(share.getUserId()).getUserName());
            sharedReturn.setFileName(file.getFileName());
            sharedReturn.setFileType(file.getFileType());
            sharedReturn.setShareTime(RunYunUtils.dateToString(share.getShareTime()));
            list.add(sharedReturn);
        }
        return list;
    }

    /**
     * 查询用户的收藏
     */
    private List<SaveReturn> getLikeInfo(Integer userId) {
        List<Share> shares = shareMapper.queryBySharedUserIdAndLike(userId, 1);
        List<SaveReturn> list = new ArrayList<>();
        for (Share share: shares) {
            SaveReturn saveReturn = new SaveReturn();
            File file = fileMapper.queryById(share.getFileId());
            saveReturn.setFileName(file.getFileName().substring(file.getFileName().lastIndexOf("/")+1));
            saveReturn.setFilePath(file.getFileName().substring(0, file.getFileName().lastIndexOf("/")+1));
            saveReturn.setFileSize(file.getFileSize());
            saveReturn.setShareUser(userMapper.queryById(share.getUserId()).getUserName());
            saveReturn.setSaveTime(RunYunUtils.dateToString(share.getLikeTime()));
            list.add(saveReturn);
        }
        return list;
    }

}
